function [ data ] = ManchesterDecode( periods )
%MANCHESTERDECODE Decodes a manchester encoded signal
%   Uses the periods between falling edges to reconstruct data from a
%   manchester encoded signal
%   Returns the data without start and stop sequence

    data = [1]; % we always assume the first falling edge is a 1 (startsequence)
    
    bitposition = 2;
    for i=1:size(periods,2)
        if periods(i) == 1 % same bit as previous
            data(bitposition) = data(bitposition - 1);
        elseif periods(i) == 2 % two switches
            data(bitposition) = 1 - data(bitposition - 1);
            data(bitposition + 1) = 1 - data(bitposition);
            bitposition = bitposition + 1;
        elseif periods(i) == 1.5 % 0 0 1 or 1 0
            if i > 1 && data(bitposition-1) == 0 % A switch after a 0 0 is also 1.5 periods
                data(bitposition) = data(bitposition - 1);
                bitposition = bitposition + 1;
            end
            data(bitposition) = 1 - data(bitposition - 1);
        else % This should never happen
            disp(['Unknown period between edges: ', periods(i)]);
        end
        bitposition = bitposition + 1;
    end
    
    % remove our assumed 1 as it's the start sequence
    data = data(2:end);
end